<template>
  <div class="app-container">
    <comprehensive-table
						ref="tableName"
            @selection-change="selectionchange" 
            :columns="column" :data="data" @reset="reset" @onSubmit="onSubmit" @custom-size-change="handleCustomSizeChange" @custom-select-change="handleCustomSelectChange"> 
			<template v-slot:avatar="{ row }">
				<img :src="getImage(row.avatar)" alt="头像展示" width="100" height="100">
			</template>
      <template v-slot:btn>
       <div style="display: flex;justify-content: flex-end">
         <el-button type="primary" @click="add"><el-icon><plus /></el-icon> 添加</el-button>
         <el-button type="danger" @click="batchDelete"><el-icon><delete /></el-icon>批量删除</el-button>
       </div>
      </template>
      <!-- <template v-slot:sex="scope">{{scope.row.sex?'男':'女'}}</template> -->
      <template v-slot:operation="scope">
        <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="edit(scope.row)"
        >
          编辑
        </el-button>
        <el-button
            @click="del(scope.row)"
            type="danger"
            size="small"
            icon="Delete"
        >
          删除
        </el-button>
				<el-button
				    @click="revise(scope)"
				    :type="scope.row.state? 'danger': 'success'"
				    size="small"
				    icon="Delete"
				>
				  {{scope.row.state ? '禁用' : '启用'}}
				</el-button>
				
      </template>
			
    </comprehensive-table>

    <el-dialog
        :visible.sync="dialogVisible"
            :title="title"
            width="50%"
    >
      <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="rules"
              label-width="120px"
              class="demo-ruleForm"
              :size="formSize"
      >
        <el-form-item label="用户名" prop="name">
				  <el-input v-model="ruleForm.name" />
				</el-form-item>
				<el-form-item label="身份" prop="roleId">
				  <el-select v-model="ruleForm.roleId" placeholder="身份">
				    <el-option label="管理员" value="管理员"></el-option>
				    <el-option label="普通用户" value="普通用户"></el-option>
						<el-option label="vip用户" value="vip用户"></el-option>
						<el-option label="员工" value="员工"></el-option>
				  </el-select>
				</el-form-item>
				<el-form-item label="部门" prop="departmentId">
				  <el-select v-model="ruleForm.departmentId" placeholder="部门">
				    <el-option label="研发部" value="研发部"></el-option>
				    <el-option label="测试部" value="测试部"></el-option>
						<el-option label="管理部" value="管理部"></el-option>
						<el-option label="用户部" value="用户部"></el-option>
						<el-option label="护送部" value="护送部"></el-option>
				  </el-select>
				</el-form-item>
				<el-form-item label="上传图片" prop="avatar">
				    <!-- 上传按钮 -->
						<el-upload v-if="isFileUpload===true"
						:auto-upload='false'
						:file-list="fileList"
						:headers="{'Authorization':'jdk'}"
						:on-change="handleChange"
						:on-remove="handleRemove"
						action=""
						drag
						list-type="picture"
						style="width: 70%;">
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
				
				<el-form-item label="积分" prop="integral">
				  <el-input v-model="ruleForm.integral" type="number"/>
				</el-form-item>
				<el-form-item label="性别" prop="sex" >
				  <el-select v-model="ruleForm.sex" placeholder="请选择性别">
				    <el-option label="男"  value="男"></el-option>
				    <el-option label="女" value="女"></el-option>
				  </el-select>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
				  <el-input v-model="ruleForm.phone" />
				</el-form-item>
				<el-form-item label="邮箱Email" prop="email">
				  <el-input v-model="ruleForm.email" />
				</el-form-item>
      </el-form>
			
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleClose('ruleFormRef')"
        >确定</el-button
        >
      </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
var dayjs = require('dayjs')
  import ComprehensiveTable from './components/comprehensive.vue'
	import axios from 'axios'
	
  const data = []
  // for(let i=0;i<100;i++){
  //   data.push({
  //     date: '2016-05-02',
  //     name: '王五'+i,
  //     types: '纸品类',
		// 	store:'五华区121大街店',
		// 	orderNum:'0120352145' + i ,
  //     admin:"admin",
  //     checked:true,
  //     id:i+1,
  //     age:0,
  //     remark:'早点来',
  //     address: '上海市普上海',
  //     zip: 200333,
		// 	weight:'10-20kg',
		// 	price:'100',
			
  //   })
  // }
  const column = [
		{type:'selection', width:60 },
		{name:'id', label: 'id',inSearch:true, valueType:'input',width:60, },
		{name:'name', label: '用户名',		width:140},
		{name:'roleId', label: '身份',inSearch:true, valueType:'input',width:80, },
		// {name:'storesId', label: '所属商铺', valueType:'input',width:80, },
		{name:'departmentId', label: '部门', valueType:'input',width:80, },
		{name:'avatar', label: '头像',width:130,slot: true },
	  {name:'stateText', label: '账号状态', inSearch:true, valueType:'input', width:100 },
		{name:'sex', label: '性别', width:60 },
		{name:'integral', label: '积分',		width:80},
		{name:'phone', label: '电话',	inSearch:true,	valueType:'input',	width:150},
		{name:'email', label: '邮箱Email',		width:200},
    {name:'operation',slot:true,fixed:'right',width:230 }
  ]
  export default {
    components:{
      ComprehensiveTable
    },
    data(){
      return{
        data,
        column,
        formSize:'default',
        ruleForm:{
          name: '',
					roleId:'普通用户',
					avatar:'null',
					integral:0,
					stateText:'',
					departmentId:null,
					sex:'',
          phone:'',
					email:'',
					
        },
        rules:{
					roleId: [
					 {  message: '请选择一个选项', trigger: 'change' }
					],
					avatar: [
					  {  message: '请上传头像', trigger: 'change' }
					],
					integral: [
					 {required: true, message: '请输入数字', trigger: 'blur' }
					],
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 1, max: 9, message: '名字不能超过9位', trigger: 'blur' },
          ],
          sex: [
            {required: true,message: '请选择性别',trigger: 'change',},
          ],
					phone: [
						{ required: true, message: '手机号码不能为空', trigger: 'blur' },
						{ pattern: /^\d{11}$/, message: '手机号码必须为11位数字', trigger: 'blur' }
          ],
					departmentId:[
						{ message: '请选择选项', trigger: 'change'}
					],
					email: [
					  { message: '邮箱不能为空', trigger: 'blur' },
					  { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '邮箱格式不正确', trigger: 'blur' }
					],
        },
        dialogVisible:false,
        title:'新增',
        rowObj:{},
        selectObj:[],
				// 分页查询
				currentPage1: 1,
				totalPages: 1,
				input: '',
				counts: 0,
				page: 1,
				pageSize: 10000,
				departmentList:'',
				fileList:[],
				isFileUpload:true,
      }
    },
		created() {
		  this.fetchData();
		},
    methods:{
			fetchData() {
				
	      axios.get('http://43.136.172.73/api/v1/admin/page', {
	        params: {
	          page:  this.page,
	          pageSize:this.pageSize,
	        },
					headers:{
						Authorization:''
					}
	      })
	      .then(response => {
	        this.data = response.data.data.records;
					// console.log(response);
					this.data.map(item=>{
						item.roleId = item.roleId == 0 ? "管理员" :(item.roleId == 1 ? "普通用户" :(item.roleId == 2 ? "vip用户" : (item.roleId == 3 ? "员工" : '')));
						item.sex = item.sex ? "男" : "女" ;	
						item.stateText = item.state ? '正常':'封禁中';
						// item.avatar = this.getImage(item.avatar);
					})
					axios.get('http://43.136.172.73/api/v1/department/list', {
							headers:{
								Authorization:''
							}
						})
						.then(response => {
							console.log(response);
							this.departmentList = response.data.data;
							for (let i = 0; i < this.data.length; i++) {
							  // const departmentId = this.data[i].departmentId;
							  for (let j = 0; j < response.data.data.length; j++) {
							    // const currentV2Item = response.data[j];
							    // const id = response.data[j].id;
							    if (this.data[i].departmentId === response.data.data[j].id) {
							      this.data[i].departmentId = response.data.data[j].name;
							      break;
							    }
							  }
							}
						})
						.catch(error => {
						  console.error('Error:', error);
						});
	      })
	      .catch(error => {
	        console.error('Error:', error);
	      });
	    },
	    
		handleChange(file, fileList) {
			if (fileList.length > 1) {
			  fileList.splice(0, 1);
			  this.$message.warning('只能上传一个图片，请先删除之前的图片！');
			}
		    this.fileList = fileList;
		    console.log(fileList)
		},
		handleRemove(file, fileList) {
		    const index = this.fileList.indexOf(file);
		    if (index !== -1) {
			    this.fileList.splice(index, 1);
		    }
		   },
	  submitUpload() {
	    		   // 向后端发送上传请求
	          // 在这个方法中，将选择的文件列表放入名为files的集合中，以便发送给后端
	          const formData = new FormData();
	          this.fileList.forEach(file => {
	            formData.append('files', file.raw);
	          });
	          // 发送上传请求
	          axios.post("http://43.136.172.73/api/v1/account/upload/files", formData,{
							headers:{
								Authorization:''
							}
						}).then(res => {
	            // 处理返回的数据
							console.log(res);
							
	            if (res.data.code === 200) {
	              const imagesUrlList = res.data.data[0];
								this.ruleForm.avatar=imagesUrlList
								console.log(this.ruleForm.avatar);
								console.log(this.ruleForm);
	              // 清空fileList
	              this.fileList = [];
	    
	            } else {
	              console.error(res.data.message);
	            }
	          });
	    	   
	          
	        },
			getImage(image) {
				return `http://43.136.172.73/api/v1/file/download?fileName=${image}`
			},
      async handleClose(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (valid) {
              let obj = {
                // id:Date.now(),
                ...this.ruleForm,
              }
							console.log(obj);
							if(this.ruleForm.avatar !== null){
								this.submitUpload();
							}
							console.log("wocao  ",this.ruleForm);
							console.log(" 你他妈的",this.ruleForm.avatar);
              if(this.title==='新增'){
                this.data = [obj,...this.data]
								// console.log(obj.roleId);
								// console.log(obj);
								obj.state = true ;
								obj.roleId = obj.roleId == "管理员" ? 0 :(obj.roleId == "普通用户" ? 1 :(obj.roleId == "vip用户" ? 2 : (obj.roleId == "员工" ? 3 : '3')));
								obj.sex = obj.sex == "男" ? 1 : 0 ;
								for(let i = 0;i<this.data.length ; i++){
								  for (let j = 0; j < this.departmentList.length; j++) {
								    if (this.data[i].departmentId ===this.departmentList[j].name) {
								      this.data[i].departmentId = this.departmentList[j].id;
								      break;
								    }
								  }
								}
								console.log(obj);
								// setTimeout(() => {
								
								axios.post('http://43.136.172.73/api/v1/admin',{
										sex: obj.sex,
										state: obj.state,
										name: obj.name,
										avatar:this.ruleForm.avatar,
										departmentId:obj.departmentId,
										integral: obj.integral,
										email: obj.email,
										phone: obj.phone,
										roleId: obj.roleId,
										departmentId:obj.departmentId
									},{
										headers:{
											Authorization:''
										},
									}).then(response => {
										console.log(response.data); // 处理响应结果
										this.$message.success('添加成功');
										
										this.fetchData();
									})
									.catch(error => {
										console.error(error); // 处理请求错误
									})	
										
									// },500)
                this.fetchData()
              }else {
								// console.log(this.data);
                
								obj.roleId = obj.roleId == "管理员" ? 0 :(obj.roleId == "普通用户" ? 1 :(obj.roleId == "vip用户" ? 2 : (obj.roleId == "员工" ? 3 : '3')));
								obj.sex = obj.sex == "男" ? 1 : 0 ;
								obj.integral=parseInt(obj.integral) 
								obj.roleId=parseInt(obj.roleId) 
								for(let i = 0;i<this.data.length ; i++){
								  for (let j = 0; j < this.departmentList.length; j++) {
								    if (this.data[i].departmentId == this.departmentList[j].name) {
								      this.data[i].departmentId = this.departmentList[j].id;
								      break;
								    }
								  }
								}
								// console.log(this.data);
								console.log("obj" , obj);
								setTimeout(() => {
									axios.put('http://43.136.172.73/api/v1/admin/update', {
										name: obj.name,
										integral: obj.integral,
										avatar:this.ruleForm.avatar,
										sex:obj.sex,
										id:this.rowObj.id,
										email:obj.email,
										roleId:obj.roleId,
										phone:obj.phone ,
										
									},{
										headers:{
											Authorization:''
										}
								})
								  .then(response => {
								    console.log(response);
										this.$message.success('修改成功')
										  for (let j = 0; j < this.departmentList.length; j++) {
										    if (obj.departmentId == this.departmentList[j].name) {
										      obj.departmentId = this.departmentList[j].id;
										      break;
										    }
										  }
											// console.log(this.rowObj.id,obj.departmentId);
										axios.put('http://43.136.172.73/api/v1/account/modify_user_type',null,  {
											params: {
												userId: this.rowObj.id,
												departmentId: obj.departmentId
											},
											headers:{
												Authorization:''
											}
										})
										  .then(response => {
										    console.log(response);
												this.$message.success('修改成功')
												this.fetchData();
										  })
										  .catch(error => {
										    console.error(error);
										  })
								  })
								  .catch(error => {
								    console.error(error);
								  })
									},1000)
              }
              this.dialogVisible = false
							
              // console.log('submit!',obj)
            } else {
              console.log('error submit!', fields)
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      add(){
        this.title='新增'
        this.dialogVisible = true
      },
      batchDelete(val){
				console.log(val);
        if(!this.selectObj.length){
          return this.$message.error('未选中任何行')
        }
        this.$confirm(
            '你确定要删除选中项吗?',
            '温馨提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              draggable: true,
            }
        )
            .then(() => {
              // console.log(this.selectObj);
              const idArray = [];
              this.selectObj.map(item => idArray.push(item.id));
              // console.log(idArray);
              const url = 'http://43.136.172.73/api/v1/admin/deletes';
              	axios.delete(url, {
              	  data: idArray, // 将idArray作为请求体数据
              	  headers: {
              	    Authorization:'dsa' 
              	  },
              	}).then(response => {
                  // 处理成功响应
              		console.log(response);
              		this.$message.success('删除成功')
              		this.fetchData()
                })
                .catch(error => {
                  // 处理错误
                })
            })
            .catch(() => {

            })
      },
      selectionchange(val){
				console.log(val);
        // this.selectObj = val
				// const selectedRows = this.$refs.tableName.getSelection();
				// console.log(selectedRows);
      },
      edit(row){
        this.title='编辑'
        this.rowObj = row
        this.dialogVisible = true
        this.ruleForm.name = row.name
				this.ruleForm.roleId = row.roleId
				this.ruleForm.integral = row.integral
				this.ruleForm.sex = row.sex 
				this.ruleForm.phone = row.phone
				this.ruleForm.email = row.email
				this.ruleForm.departmentId = row.departmentId
				// console.log(row);
      },
      del(row){
        this.$confirm(
            '你确定要删除当前项吗?',
            '温馨提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
              draggable: true,
            }
        )
            .then(() => {
							// console.log(row.id);
							const idArray = [];
							idArray.push(row.id);
							// console.log(idArray);
							const url = 'http://43.136.172.73/api/v1/admin/deletes';
							const headers = {Authorization:'dsa'}
							setTimeout(() => {
								axios.delete(url, {
								  data: idArray, // 将idArray作为请求体数据
								  headers: {
								    Authorization:'dsa' 
								  },
								}).then(response => {
							    // 处理成功响应
									console.log(response);
									this.$message.success('删除成功')
									this.fetchData()
							  })
							  .catch(error => {
							    // 处理错误
							  })
								},1000)
              
            })
            .catch(() => {

            })
      },
			revise(scope){
				if(scope.row.state == true){
					this.$confirm(
				    '你确定要封禁该账号吗?',
				    '温馨提示',
				    {
				      confirmButtonText: '确定',
				      cancelButtonText: '取消',
				      type: 'warning',
				    })
				    .then(() => {
							setTimeout(() => {
							axios.put('http://43.136.172.73/api/v1/admin/state',null,  {
							  params: {
							    userId: scope.row.id,
							    status: "false"
							  },
								headers:{
									Authorization:''
								}
							})
							  .then(response => {
									console.log(scope);
							    console.log(response.data);
									this.$message.success('启用成功')
									this.fetchData();
							  })
							  .catch(error => {
							    console.error(error);
							  })},1000);
				      
				    })
				    .catch(() => {
				
				    })
				}else{
					this.$confirm(
					  '你确定要启用该账号吗?',
					  '温馨提示',
					  {
					    confirmButtonText: '确定',
					    cancelButtonText: '取消',
					    type: 'warning',
					    draggable: true,
					  })
					  .then(() => {
						setTimeout(() => {
							axios.put('http://43.136.172.73/api/v1/admin/state', null, {
							  params: {
							    userId: scope.row.id,
							    status: "true"
							  },
								headers:{
									Authorization:''
								}
							})
							  .then(response => {
									this.$message.success('启用成功')
									this.fetchData();
							  })
							  .catch(error => {
							    console.error(error);
							  })},2000);
					    
					  })
					  .catch(() => {
									
					  })
				}
			},
      reset(){
        this.$message.success('触发重置方法');
				this.fetchData();
      },
      onSubmit(childData){
				console.log(childData);
				const obj = childData
				if(obj.id === ""){
					obj.id =null
				}
				if(obj.roleId === ""){
					obj.roleId =null
				}
				if(obj.phone === ""){
					obj.phone =null
				}
				if(obj.stateText === ""){
					obj.stateText =null
				}
					if((['管理员','普通用户','vip用户','员工'].includes(obj.roleId)) || (['正常', '封禁中'].includes(obj.stateText)) || obj.id !== null || obj.phone !== null )	{
						
						obj.stateText = obj.stateText == "正常" ? 1 : (obj.stateText == "封禁中" ? 0 : null );
						obj.roleId = obj.roleId == "管理员" ? 0 :(obj.roleId == "普通用户" ? 1 :(obj.roleId == "vip用户" ? 2 : (obj.roleId == "员工" ? 3 : null )));
							if ((obj.id === null && obj.phone === null && obj.roleId === null) ||
									(obj.id === null && obj.phone === null && obj.stateText === null) ||
									(obj.id === null && obj.roleId === null && obj.stateText === null) ||
									(obj.phone === null && obj.roleId === null && obj.stateText === null)) {
						    // 执行函数
								console.log(obj);
								const arr = {
									name:null,
									type:null
								};
								console.log(arr);
								if(obj.id !== null) {
									arr.name=obj.id,
									arr.type="id"
								}else if(obj.roleId !== null) {
									arr.name=obj.roleId,
									arr.type="role"
								}else if(obj.phone !== null) {
									arr.name=obj.phone,
									arr.type="phone"
								}else if(obj.stateText !== null) {
									arr.name=obj.stateText,
									arr.type="state"
								}
								console.log(arr);
									axios.get('http://43.136.172.73/api/v1/admin/page', {
										params: {
											page: 1,
											pageSize:100000,
											name:arr.name,
											type:arr.type
										},
										headers:{
											Authorization:''
										}
									})
									.then(response => {
										console.log(response);
										this.data = response.data.data.records;
										this.data.map(item =>{
											item.roleId = item.roleId == 0 ? "管理员" :(item.roleId == 1 ? "普通用户" :(item.roleId == 2 ? "vip用户" : (item.roleId == 3 ? "员工" : '')));
											item.sex = item.sex ? "男" : "女" ;	
											item.stateText = item.state ? '正常':'封禁中'
										})
										console.log(childData);
										childData.stateText = childData.stateText == 1 ? "正常" : (childData.stateText == 0 ? "封禁中" : null );
										childData.roleId = childData.roleId == 0 ?  "管理员" :(childData.roleId == 1 ? "普通用户" :(childData.roleId == 2 ? "vip用户"  : (obj.roleId == 3 ? "员工"  : null )));
										this.$message.success('触发查询方法');
										// this.$eventBus.$emit('total-updated', this.total);
										// this.totalPages = responseData.totalPages;
									})
									.catch(error => {
										console.error('Error:', error);
									});
								} else{
									this.$message.warning('只能输入一个数据，进行单次查询');
								}
					}else{
						this.$message.warning('请正确输入数据,身份:管理员、普通用户、vip用户、员工。账号状态:正常、封禁中');
					}
				
				
        
      },
			reloadPage() {
			 
			},
			handleSizeChange(val){
				console.log(val);
			  console.log(`${val} items per page`);
			},
			handleCurrentChange(val){
				console.log(val);
			  console.log(`current page: ${val}`)
			  this.currentPage = val;
			},
			handleCustomSizeChange(val) {
			    // this.page = val;
					console.log(val);
			    // 其他逻辑...
					this.pageSize=val;
					axios.get('http://43.136.172.73/api/v1/admin/page', {
					  params: {
					    page:  this.page,
					    pageSize:this.pageSize,
					  },
						headers:{
							Authorization:''
						}
					})
					.then(response => {
					  this.data = response.data.data.records;
						console.log(response);
						this.data.map(item=>{
						
							item.roleId = item.roleId == 0 ? "管理员" :(item.roleId == 1 ? "普通用户" :(item.roleId == 2 ? "vip用户" : (item.roleId == 3 ? "员工" : '')));
							item.sex = item.sex ? "男" : "女" ;	
							item.stateText = item.state ? '正常':'封禁中'
						})
					})
					.catch(error => {
					  console.error('Error:', error);
					});
			},
			handleCustomSelectionChange(val) {
			    // 使用 val 做进一步的处理
					console.log(val);
			    // ...
			},
			handleCustomSizeChange(val){
				console.log(val);
				this.pageSize = val;
				console.log(this.pageSize);
				const totalPage = Math.ceil(this.totalItems / this.pageSize);
				// 处理当前页超出新的总页数的情况
				if (this.currentPage > totalPage) {
				  this.currentPage = totalPage;
				}
				
			},
			handleCustomSelectChange(val){
				console.log(val);
				this.selectObj = val;
			}
    },
		computed: {
		  
		},
		mounted() {
			
		}
  }

</script>
<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
